// https://leetcode-cn.com/problems/decode-string/

function decodeString(s: string): string {
    let i = 0;
    const result: string[] = [];

    while (i < s.length) {
        if (isDigit(s[i])) {
            result.push(getDigit());
        } else if (isAlpha(s[i]) || s[i] === '[') {
            result.push(s[i]);
            i++;
        } else {
            i++;
            const letters = getLetters();
            result.push(letters);
        }
    }

    return result.join('');

    function getLetters(): string {
        let c;
        const letters = [];
        while ((c = result.pop()) !== '[') {
            letters.unshift(c);
        }
        const num = parseInt(result.pop() || '1', 10);
        return new Array(num).fill(letters.join('')).join('');
    }

    function isAlpha(c: string): boolean {
        const [a, z, nc] = ['a', 'z', c].map((item) => item.charCodeAt(0));
        return nc >= a && nc <= z;
    }

    function isDigit(c: string): boolean {
        return '0123456789'.indexOf(c) !== -1;
    }

    function getDigit(): string {
        const result = [];
        while (isDigit(s[i])) {
            result.push(s[i++]);
        }

        return result.join('');
    }
}
